package edu.sias.dao;

import edu.sias.pojo.Post;
import edu.sias.util.DButil;
import javafx.geometry.Pos;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

//检索操作的数据层   直接和数据库对接
public class SearchDao {

    public List<Post> findMsg(String keyMsg) throws SQLException {
        //连接数据库。获取数据
        //手动模拟数据
        ArrayList<Post> posts = new ArrayList<>();
        //定义sql语句
        String sql = "select * from post where title like ?";
        //调用select执行查询操作   ResultSet代表的是查询的结果
        ResultSet rs = DButil.select(sql,new Object[]{'%'+keyMsg+'%'});
        //遍历结果集ResultSet
        while (rs.next()){
            //将获取到的数据中的每个字段进行解析
            int id = rs.getInt("id");
            String title = rs.getString("title");
            String text = rs.getString("text");
            int click = rs.getInt("click");
            String url = rs.getString("url");
            //每一条数据保存到对应的对象中
            Post post = new Post(id, title, text, click, url);
            //将每一条数据对应的对象放入一个集合中
            posts.add(post);
        }

        //将数据返回
        return posts;
    }

    /**
     * 数据层 根据文章id查询详情信息
     * @param id
     * @return Post 具体的详情信息
     */
    public Post queryPostById(int id) throws SQLException {
        String sql =
                "select * from post where id =?";
        ResultSet rs = DButil.select(sql, new Object[]{id});
        Post post = null;
        //获取结果集中的数据
        while (rs.next()){
            int i = rs.getInt("id");
            String title = rs.getString("title");
            String text = rs.getString("text");
            int click = rs.getInt("click");
            String url = rs.getString("url");
            post = new Post(i,title,text,click,url);
        }
        return post;

    }

    //根据文章类别查询信息
    public List<Post> queryPostByCategoryId(int id) throws SQLException {
        String sql
                = "select p.*,c.name " +
                "from post p,category c " +
                "where p.category_id=c.id " +
                "and p.category_id=?";

        List<Post> list = new ArrayList<>();
        //执行sql
        ResultSet rs
                = DButil.select(sql, new Object[]{id});

        while (rs.next()){
            int i = rs.getInt("id");
            String title = rs.getString("title");
            String text = rs.getString("text");
            int click = rs.getInt("click");
            String url = rs.getString("url");
            String c_name = rs.getString("name");
            Post post =
                    new Post(i,title,text,click,url,id,c_name);
            list.add(post);
        }
            return list;

    }
}
